/**
 * 
 */
package com.googlecode.dynargs.extractor;

import java.lang.reflect.ParameterizedType;
import java.util.Collection;

import com.googlecode.dynargs.model.type.CollectionType;
import com.googlecode.dynargs.model.type.Type;

/**
 * @author Federico De Faveri defaveri@gmail.com
 *
 */
public class CollectionExtractor implements TypeExtractor<CollectionType> {

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean canExtract(TypeToken typeToken) {
		Class<?> clazz = typeToken.getRawType();
		return Collection.class.isAssignableFrom(clazz);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public CollectionType extract(ModelExtractor modelExtractor, TypeToken typeToken) {
		
		//java.lang.reflect.Type type = ReflectionUtil.getCollectionElementType(clazz, Collection.class);
		//Class<?> genericType = ReflectionUtil.getRawType(type);
				
		java.lang.reflect.Type genericType = typeToken.getGenericType();
		ParameterizedType parameterized = (ParameterizedType) genericType;
		Class<?> argumentType = (Class<?>)parameterized.getActualTypeArguments()[0];
		
		String id = ((Class<?>)parameterized.getRawType()).getName();
		id += "<" + argumentType.getName() + ">";
		
		TypeToken argument = new TypeToken(argumentType);
		
		Type collectionType = modelExtractor.extract(argument);
		return new CollectionType(id, collectionType);
	}

}
